import {defineStore} from 'pinia'
import {computed, ref} from 'vue'

import { useUserStore } from './user'
import { storeToRefs } from 'pinia'
import {insertCartAPI, findNewCartListAPI, delCartAPI} from '@/network/cart'

export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    
    const isLogin = computed(() => userStore.userInfo.token)
    // console.log(isLogin);
    // 1. 定义state
    let cartList = ref([])

    // 获取购物车列表接口
   async function updateNewList() {
        const res = await findNewCartListAPI() 
            cartList.value = res.result
            console.log(res);
    }
    // 2. 定义action 添加商品
    const addCart = async (goods) => {  
        const {skuId, count} = goods
        if(isLogin.value) {
            insertCartAPI({skuId, count}) // 加入购物车接口
            updateNewList() // 更新
        } else{
            const item = cartList.value.find((item) => {
            // 总是忘记写return 以至于找不到相同的skuId商品，后续判断老是走else
            return item.skuId === goods.skuId
            })

            // console.log(item);

            if (item) {
                item.count += goods.count
            } else {
                cartList.value.push(goods)
            }
        }
       
    }

    // 3. 定义删除商品
    const delCart = async (skuId) => {
        if (isLogin.value) {
            delCartAPI([skuId]) // 删除购物车接口
            updateNewList() // 更新
        } else {
           //     // (1). 找到要删除的下标值
        //   const index = cartList.value.findIndex(item => {
        //         return skuId === item.skuId
        //     })
        //     console.log(index);
        //     cartList.value.splice(index, 1)
        // (2). 使用数组过滤方法 - filter 过滤掉删除的商品，重新赋值给cartList
        cartList.value = cartList.value.filter(item => {
                return skuId !== item.skuId
            })
        }
    
    }

    // 退出登录，清除本地购物车
    const clearCart = () => {
        cartList.value = []
    }

    // 4. 计算商品，定义计算属性
    // (1) 总的数量
    const totalCount = computed(() => {
        // 计算属性也需return 老是在这犯错误，检查了好久
       return cartList.value.reduce((prev, current) => {
            return prev + current.count
        }, 0)
    })
    // (2) 总价 所有count * price 之和
    const totalPrice = computed(() => {
        return cartList.value.reduce((prev, current) => {
            return prev + current.count * current.price
        }, 0)
    })

    // 5. 列表购物车单选
    const goodcheck = (selected, skuId) => {
        // 通过skuId找到要修改的那一项，把它的selected修改为传过来的参数selected
       const item = cartList.value.find((item) => {
            return item.skuId === skuId
        })
        // console.log(item);
        item.selected = selected
    }

    // 6. 是否全选
    // (1) 点击每一项，决定全选按钮是否选中
    const isAll = computed(() => {
        return cartList.value.every((item) => {
            // console.log(item.selected);
            return item.selected
        })
    })

    // (2) 点击全选按钮，下面全部选中
    const allcheck = (selected) => {
        console.log(selected);
        cartList.value.forEach((item) => {
            item.selected = selected
        })
    }

    // 列表购物车，已选择数量
    const selectedCount = computed(() => {
        return cartList.value.filter(item => {
                return item.selected === true

            }).reduce((prev, current) => {
                return prev + current.count
            }, 0)
    })

    // 已选择商品价格合计
    const selectedPrice = computed(() => {
        return cartList.value.filter(item => {
                return item.selected === true

            }).reduce((prev, current) => {
                return prev + current.count * current.price
            }, 0)
    })

    return {
        cartList,
        addCart,
        delCart,
        totalCount,
        totalPrice,
        goodcheck,
        isAll,
        allcheck,
        selectedCount,
        selectedPrice,
        clearCart,
        updateNewList
    }
}, {
    persist: true
})